package top.firejames.util;

import top.firejames.util.FileUtil;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * 随机类
 */
public class RandomUtils {

    public final static Random RANDOM = new Random();


    /**
     * 获取无重复随机序列
     *
     * @param amount
     * @return
     */
    public static int[] getRandomSequence(int amount) {
        int[] sequence = new int[amount];
        int[] output = new int[amount];
        for (int i = 0; i < amount; i++) {
            output[i] = i;
        }
        int max = amount;
        for (int i = 0; i < amount; i++) {
            int num = random(0, max--);
            sequence[i] = output[num];
            output[num] = output[max];
        }
        return sequence;
    }

    /**
     * 从【min, max】区间中随机一个数字
     *
     * @param min
     * @param max
     * @return
     */
    public static int random(int min, int max) {
        if (min > max) {
            int temp = min;
            max = min;
            min = temp;
        }
        return RANDOM.nextInt(max) % (max - min + 1) + min;
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        closeFile();
        int[] sequence = getRandomSequence(1000000);
        StringBuffer stringBuffer = new StringBuffer(10000);

        for (int i = 1; i <=sequence.length; i++) {
            stringBuffer.append(sequence[i-1]).append("\n");
            try {
                if (i % 10000 == 0 && i != 0) {
                    if (i == sequence.length) {
                        stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
                    }
                    FileUtil.write("mergeNumbers.txt", stringBuffer.toString());

                    stringBuffer.delete(0, stringBuffer.length());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        try {
//            FileUtil.close("mergeNumbers.txt");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        System.out.println(System.currentTimeMillis() - start);
    }

    public static void closeFile() {
        File file = new File("mergeNumbers.txt");
        if (file.exists()) {
            file.delete();
        }


    }


}
